using System;
using System.Threading;

namespace RxjhServer
{
	public class WUserBase<TContext> : IWUser<TContext>
	{
		[NonSerialized]
		private ReaderWriterLockSlim _objLock = Locks.GetLockInstance(LockRecursionPolicy.NoRecursion);

		private string _credentials = string.Empty;

		public DateTime Timestamp
		{
			get;
			set;
		}

		public int Index
		{
			get;
			set;
		}

		public bool Invalid
		{
			get;
			set;
		}

		public TContext Context
		{
			get;
			set;
		}

		public string Credentials => _credentials;

		public IDisposable ReadLock => new ReadOnlyLock(_objLock);

		public IDisposable UpdateLock => new ReadLock(_objLock);

		public IDisposable WriteLock => new WriteLock(_objLock);

		public virtual void Reset()
		{
			_credentials = Guid.NewGuid().ToString();
			Context = default(TContext);
		}

		public bool Authentication(string credentials)
		{
			return !string.IsNullOrEmpty(_credentials) && !string.IsNullOrEmpty(credentials) && !(_credentials != credentials);
		}

		public WUserBase()
		{
			Index = -1;
			Timestamp = DateTime.MinValue;
			Invalid = true;
		}

		public override string ToString()
		{
			return $"{Index}-{Timestamp}";
		}
	}
}
